package com.lt.controller;

import com.lt.entity.Medicine;
import com.lt.service.MedicineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/medicines")
public class MedicineController {

    @Autowired
    private MedicineService medicineService;

    @PostMapping
    public Result save(@RequestBody Medicine medicine){
        boolean flag = medicineService.save(medicine);
        return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR,flag);
    }

    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id){
        boolean flag = medicineService.deleteById(id);
        return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR,flag);
    }

    @PutMapping
    public Result update(@RequestBody Medicine medicine){
        boolean flag = medicineService.update(medicine);
        return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR,flag);
    }

    @GetMapping
    public Result getAll(){
        List<Medicine> medicineList = medicineService.getAll();
        Integer code = medicineList != null ? Code.GET_OK : Code.GET_ERR;
        String msg = medicineList != null ? "" : "数据查询失败，请重试";
        return new Result(code,medicineList,msg);
    }

    @GetMapping("/{id}")
    public Result getAll(@PathVariable Integer id){
        Medicine medicine = medicineService.getById(id);
        Integer code = medicine != null ? Code.GET_OK : Code.GET_ERR;
        String msg = medicine != null ? "" : "数据查询失败，请重试";
        return new Result(code,medicine,msg);
    }
}
